package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private MongoTemplate template;
    @Autowired
    private BannerRepository repository ;
    @Override
    public void save(Banner Banner) {
        Banner.setId(null);
        repository.save(Banner);
    }

    @Override
    public void update(Banner Banner) {
        repository.save(Banner);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> list() {
        return repository.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        Query query = new Query();

        long count = template.count(query, Banner.class);
        if(count==0){
            return Page.empty();
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize() ,Sort.Direction.DESC ,"sequence");
        query.with(pageable);
        List<Banner> banners = template.find(query, Banner.class);
        return new PageImpl<>(banners,pageable ,count );
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        if(banner.getId()==null){
            this.save(banner);
        }else {
            this.update(banner);
        }
    }

    @Override
    public List<Banner> queryByStateAndType(int stateNormal, int typeTravel) {
        Pageable pageable = PageRequest.of(0,5 ,Sort.Direction.DESC ,"sequence");
        List<Banner> banners = repository.findByStateAndType(stateNormal,typeTravel,pageable);
        return banners;
    }
}
